import { Component, ViewChild } from '@angular/core';

import { Storage } from '@ionic/storage';

import { AlertController, App, ModalController, NavController, Content, ActionSheetController, Navbar } from 'ionic-angular';

import { FlowListService } from './list.service';

import { Config } from '../../../providers/config';

import { TaskDetailPage } from '../../../pages/task/detail/detail.component';

import _ from 'lodash';
import {FlowQueryPage} from "../query/query.component";
import {DraftDetailPage} from "../../draft/detail/detail.component";
import {TaskDetailService} from "../../task/detail/detail.service";

@Component({
  selector: 'page-flow-list',
  templateUrl: './list.html',
  providers: [FlowListService, TaskDetailService]
})
export class FlowListPage {
	moa_page_name: any = "page-flow-list";
  moa_page_explain: any = "流程中心";

  _ = _;
  // 列表数据
  listData;

  // 是否可以加载更多
  isLoadMore = true;
  // 页码
  pageIndex = 1;
  // 关键字
  keyWord = "";
  // 流程状态
  flowStatus = "";
  // 导航栏标题
  title = "全部流程";

  queryCondition = null;

  @ViewChild(Content) content: Content;

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public flowListService: FlowListService,
    private actionSheetCtrl: ActionSheetController,
    public storage: Storage,
    public config: Config,
    public taskDetailService: TaskDetailService
  ) {
    this.storage.remove("advancedQueryCondition");
    this.initQueryCondition();
    // 初始化数据
    this.loadListData(1, null, null);
  }
  /**
   * [loadListData 加载列表数据]
   * @param {[type]} page           [页码]
   * @param {[type]} title          [标题关键字]
   * @param {[type]} infiniteScroll [加载更多组件]
   * @param {[type]} refresher      [下拉刷新组件]
   */
  loadListData(page, infiniteScroll, refresher) {
    this.queryCondition.flowStatus = this.flowStatus;
    var params = {
      page: page,
      /*condition: {
        "title": this.keyWord ? this.keyWord : "",
        "flowStatus": this.flowStatus ? this.flowStatus : ""
      }*/
      condition: this.queryCondition
    }

    this.flowListService.getFlowListData(params).subscribe(data => {
      if (data) {
        //console.log("##flow.list.loadListData -> data:");
        //console.info(data);
        // 如果加载第一页，则清空数据
        if (page == 1) {
          this.isLoadMore = true;
          this.listData = [];
        }
        // 把现有数据和新加载的数据合并
        this.listData = _.orderBy(_.concat(this.listData, data),["bosid"], ["desc"]);
        // 增加搜索索引
        this.pageIndex = this.pageIndex + 1;
        // 如果返回数据少于请求页数，则不再加载更多
        if (data.length < this.config.pageSize) {
          this.isLoadMore = false;
        }
      } else {
        this.listData = [];
        this.isLoadMore = false;
      }
      // complete event
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    })
  };

  /**
   * [chooseFlowStatue description]
   * [重新定义流程状态 1:全部流程,2.草稿中流程,3.审批中流程,4.已办理流程,5.被退回流程,6.已终止流程]
   */
  chooseFlowStatue() {
    var that = this;
    let actionSheet = this.actionSheetCtrl.create({
      title: '',
      buttons: [
        {
          text: "全部流程",
          handler: () => {
            that.title = "全部流程";
            that.flowStatus = '1';
            that.content.scrollTo(0, 0, 1);
            that.loadListData(1, null, null);
          }
        },
        {
          text: "草稿中流程",
          handler: () => {
            that.title = "草稿中流程";
            that.flowStatus = '2';
            that.content.scrollTo(0, 0, 1);
            that.loadListData(1, null, null);
          }
        },
        {
          text: "审批中流程",
          handler: () => {
            that.title = "审批中流程";
            that.flowStatus = '3';
            that.content.scrollTo(0, 0, 1);
            that.loadListData(1, null, null);
          }
        },
        {
          text: "已办理流程",
          handler: () => {
            that.title = "已办理流程";
            that.flowStatus = '4';
            that.content.scrollTo(0, 0, 1);
            that.loadListData(1, null, null);
          }
        },
        {
          text: "被退回流程",
          handler: () => {
            that.title = "被退回流程";
            that.flowStatus = '5';
            that.content.scrollTo(0, 0, 1);
            that.loadListData(1, null, null);
          }
        },
        {
          text: "已终止流程",
          handler: () => {
            that.title = "已终止流程";
            that.flowStatus = '6';
            that.content.scrollTo(0, 0, 1);
            that.loadListData(1, null, null);
          }
        },
        {
          text: "取消",
          role: 'cancel',
          handler: () => {
            //console.log('Cancel clicked');
          }
        }
      ]
    });

    actionSheet.present();
  }

  /**
   * [getSreserved3 description]
   * @param {[type]} num [description]
   * sreserved3字段各值分别表示：
    （1）流程审批办理结束：5；
    （2）流程还在审批中：2或者9；
    （3）流程被打回：7或者8；
    （4）流程终止掉了(非正常结束)：4或者6；
    （5）空则表示起草状态。
   */
  getSreserved3(num) {
    var retVal = "草稿";
    if (num && num != "") {
      switch (num) {
        case '2':
          retVal = "审批中";
          break;
        case '4':
          retVal = "已终止";
          break;
        case '5':
          retVal = "已办理";
          break;
        case '6':
          retVal = "已终止";
          break;
        case '7':
          retVal = "被退回";
          break;
        case '8':
          retVal = "被退回";
          break;
        case '9':
          retVal = "审批中";
          break;
      }
    }

    return retVal;
  }


  search() {
    //console.log("##search 关键字：" + this.keyWord);
    this.content.scrollToTop(); // 将滚动的位置重新置顶
    this.initQueryCondition();
    this.queryCondition.title = this.keyWord ? this.keyWord : "";
    this.loadListData(1, null, null);
  }

  /**
   * [goDetailPage 跳转详情页]
   * @param {[type]} item [参数]
   */
  goDetailPage(item) {
    console.info(item);
    if (this.config.allowDraftFlow.indexOf(item.bomid) > -1) {
      if (item.sreserved3) {
        if (item.sreserved3 === "") {
          this.goDraftEditPage(item);
        } else {
          console.log(item.sreserved3);
          if (item.sreserved3 === "8" || item.sreserved3 === "7") {
            this.storage.get("userInfo").then(user => {
              if (user.empid === item.empid) {
                this.taskDetailService.getWorkFlowInfo(user.loginid, item.bosid, item.bomid).subscribe(workFlowInfo => {
                  console.log("getWorkFlowInfo", workFlowInfo);
                  if (workFlowInfo) {
                    if (workFlowInfo["flowCurrNode"] === "起始节点" || workFlowInfo["flowCurrNode"].indexOf("起草") > -1) {
                      this.goDraftEditPage(item);
                    } else {
                      this.navCtrl.push(TaskDetailPage, {id: item.bosid, wkiType: "6"});
                    }
                  } else {
                    this.navCtrl.push(TaskDetailPage, {id: item.bosid, wkiType: "6"});
                  }
                });
              } else {
                this.navCtrl.push(TaskDetailPage, {id: item.bosid, wkiType: "6"});
              }
            });
          } else {
            this.navCtrl.push(TaskDetailPage, {id: item.bosid, wkiType: "6"});
          }
        }
      } else {
        this.goDraftEditPage(item);
      }
    } else {
      this.navCtrl.push(TaskDetailPage, {id: item.bosid, wkiType: "6"});
    }
  };

  goDraftEditPage(item) {
    let type = "";
    switch (item.bomid) {
      case "T_HR_ChuChai":
        type = "ccsq";
        break;
      case "T_HR_ChuJingSQ":
        type = "cjsq";
        break;
      case "T_HR_ChuQinBG":
        type = "cqbg";
        break;
      case "T_HR_GongWuWC":
        type = "gwwc";
        break;
      case "T_HR_QingJia":
        type = "qxjsq";
        break;
    }

    this.navCtrl.push(DraftDetailPage, {
      ops: "reject",
      bosid: item.bosid,
      type : type
    });
  }

  ionViewDidLoad() {

  };
  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    if (this.pageIndex != 1) {
      if (this.isLoadMore) {
        this.loadListData(this.pageIndex, infiniteScroll, null);
      } else {
        infiniteScroll.complete();
      }
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.pageIndex = 1;
    this.isLoadMore = true;
    this.loadListData(this.pageIndex, null, refresher);
  }

  /**
   * 打开高级查询页面
   */
  showAdvancedQueryModal() {
    console.log("打开Modal");
    let queryModal = this.modalCtrl.create(FlowQueryPage, {

    });
    queryModal.onWillDismiss(data => {
      if (data && data != "close") {
        this.storage.get("advancedQueryCondition")
          .then(data => {
            if (data != null) {
              console.log(data);
              this.queryCondition = data;
              this.pageIndex = 1;
              this.loadListData(this.pageIndex, null, null);
            }
          });
      }
    });
    queryModal.present();
  }

  initQueryCondition() {
    this.queryCondition = {
      "title": "",
      "flowStatus": "",
      "empid":null,
      "startDate":null,
      "endDate":null,
      "bomid":null,
      "dirid":null
    }
  }

}
